import React, {Component} from 'react';
import {Row, Col, Form, Input, Select, DatePicker, Button, Table, Icon, message, Pagination,Modal} from 'antd';
import moment from 'moment'
import './formcomponents.less';
import Fetch from "../../../../fetchAPI";

const FormItem = Form.Item;
const Option = Select.Option;
const {RangePicker} = DatePicker;

class Index extends Component {
    constructor() {
        super();
        this.state = {
            datalist: "",//数据
            fileName: "",
            expand: false,
            content: {},
            pageSize: 50,//每页显示条数
            pageIndex: 1,//当前多少页
            updateState: "",//修改状态
            total: 0,//当前数据的总条数
            filter: {},
            visible: false,
            updateStates:"",
            indexId:""

        }
    }

    componentWillMount() {
        this.props.setTitle('预售列表')
        Fetch.getPresaleLists(
            {

                "pageIndex": 1,
                "pageSize": 50
            })
            .then((res) => {
                if (res.code === "200") {
                    console.log(res, 'tableList');
                    this.setState({
                        datalist: res.result,
                        total: res.rowCount
                    })
                } else {
                    message.error("数据请求失败")
                }

            })
    }

    //展开收起功能
    toggle = () => {
        const {expand} = this.state;
        this.setState({expand: !expand});
    }

    isBtn = (str) => {
        console.log(str)
        if (str.state === 0) {
            return <span onClick={(e) => {
                this.showModal(e,str)
            }} id="1" style={{"cursor": "pointer"}}>开启预售</span>
        } else if (str.state === 1) {
            return <span onClick={(e) => {
                this.showModal(e,str)
            }} id="0" style={{"cursor": "pointer"}}>关闭预售</span>
        }
    }
    //获取修改状态
    getState = (e, str) => {

        if (e.target.innerText === "开启预售") {
            // this.updateStaet(str.id, e.target.id)
            this.setState({
                updateStates: e.target.id,
                indexId:str.id
            })
        } else {
            // this.updateStaet(str.id, e.target.id)
            this.setState({
                updateStates: e.target.id,
                indexId:str.id
            })
        }
    }
    // 修该状态
    updateStaet = (id, state) => {
        Fetch.setPresaleState(
            {
                "id": id.toString(),
                "state": state
            })
            .then((res) => {
                if (res.code === "200") {
                    console.log(res, 'tableList');
                    this.initPage()
                } else {
                    console.log("数据请求失败")
                }

            })

    }
    // 查询
    handleSearch = (e) => {
        let _this = this;
        e.preventDefault();
        let searchData = {}
        this.props.form.validateFields((err, values) => {
            let {pageSize} = this.state;
            console.log('Received values of particulars: ', values);
            // name: undefined, id: undefined, earnestType: undefined, beginTime: undefined, deliveryTime: undefined}
            if (values.name) {
                searchData.name = values.name
            }
            if (values.id) {
                searchData.id = Number(values.id)
            }
            if (values.earnestType) {
                searchData.earnestType = Number(values.earnestType)
            }
            if (values.beginTime) {
                searchData.beginTime = values.beginTime[0].format('YYYY-MM-DD HH:mm:ss')
            }
            _this.setState((state) => {
                state.filter = {...searchData};
                state.pageIndex = 1;
                state.pageSize = 50;
                return state;
            }, () => {
                _this.initPage()
            })
        });
        console.log('Received values of particulars: ', searchData);
    }
    initPage = () => {
        const that = this
        const {pageIndex, pageSize, filter, total} = that.state;
        const searchData = {...filter, pageIndex, pageSize};
        console.log(searchData)
        Fetch.getPresaleLists(
            searchData
        ).then((res) => {
            if (res.code === "200") {
                console.log(res, 'tableList');
                this.setState({
                    datalist: res.result,
                    total: res.rowCount
                })
            } else {
                console.log("数据请求失败")
            }
        })
    }
    // 重置
    handleReset = () => {
        this.props.form.resetFields();
    }
    // 分页
    onPageChange = (current, pageSize) => {
        console.log(current, pageSize)
        this.setState({
            pageIndex: current,
            pageSize: pageSize
        }, () => {
            this.initPage();
        })

    }
    //modal
    showModal = (e, str) => {
        this.setState({
            visible: true,
        });
        this.getState(e, str)
    }

    handleOk = (e) => {
        this.setState({
            visible: false,
        });
        // updateStates: e.target.id,
        //     indexId:str.id
        // this.updateStaet(str.id, e.target.id)
        this.updateStaet(this.state.indexId,this.state.updateStates)
    }

    handleCancel = (e) => {
        console.log(e);
        this.setState({
            visible: false,
        });
    }
    toView1 = () => {
        this.props.router.push(
            {
                pathname: '/app/home/add',
            }
        )
    }
    toView2 = (item) => {
        console.log(item);
        return () => {
            this.props.router.push(
                {
                    pathname: '/app/home/add',
                    query: {
                        id: item.id,
                        pid: item.rangeConditionId,
                        view: 0
                    }
                }
            )
        }
    }
    toView3 = (item) => {
        console.log(item)
        return () => {
            this.props.router.push(
                {
                    pathname: '/app/home/add',
                    query: {
                        id: item.id,
                        pid: item.rangeConditionId
                    }
                }
            )
        }
    }

    render() {
        const _this = this;
        let {content, total} = this.state;
        const {getFieldDecorator} = this.props.form;
        const labelCol = {xl: 2, lg: 3, md: 4, sm: 5, xs: 6};
        const wrapperCol = {xl: 22, lg: 21, md: 20, sm: 19, xs: 18};
        const formItemLayout = {
            labelCol: {xl: 4, lg: 6, md: 8, sm: 10, xs: 12},
            wrapperCol: {xl: 20, lg: 18, md: 16, sm: 14, xs: 12}
        }

        const columns = [
            {
                title: "预售编号",
                dataIndex: 'id',
                width: 80,
            },   {
                title: "商品列表编号",
                dataIndex: 'rangeConditionId',
                width: 80,
            },
            {
                title: "预售名称",
                dataIndex: 'name',
                width: 150,
                render(text, record) {
                    return <p>{record.name}</p>

                }
            },
            {
                title: "定金支付方式",
                dataIndex: 'earnestType',
                width: 100,
                render(text, record) {
                    return <span>{record.earnestType === 1 ? "按金额支付" : "全款支付定金"}</span>

                }
            },
            {
                title: "预售时间",
                dataIndex: 'endTime',
                width: 150,
                render(text, record) {
                    return <div>
                        <p>
                            <p>预售开始时间：{moment(record.beginTime).format("YYYY-MM-DD HH:mm:ss")}</p>
                            <p>预售结束时间：{moment(record.endTime).format("YYYY-MM-DD HH:mm:ss")}</p>
                        </p>
                    </div>

                }
            },
            {
                title: "全款支付时间",
                dataIndex: 'payBeginTime',
                width: 150,
                render(text, record) {
                    return <div>
                        <p>
                            <p>全款支付开始时间：{moment(record.payBeginTime).format("YYYY-MM-DD HH:mm:ss")}</p>
                            <p>全款支付结束时间：{moment(record.payEndTime).format("YYYY-MM-DD HH:mm:ss")}</p>
                        </p>
                    </div>


                }
            },
            {
                title: "定金支付金额",
                dataIndex: 'earnestPayPrice',
                width: 70,
            },
            {
                title: "定金抵扣金额",
                dataIndex: 'earnestRepayPrice',
                width: 70,
            },
            {
                title: "状态",
                dataIndex: 'state',
                width: 50,
                render(text, record) {
                    return <span>{record.state === 0 ? "关闭" : "开启"}</span>

                }
            },
            {
                title: "操作时间",
                dataIndex: 'createDate',
                width: 250,
                render(text, record) {
                    return <p>
                        <p>预售创建时间：{record.createDate}</p>
                        <p>预售更新时间：{record.updateDate}</p>
                    </p>
                }
            },
            {
                title: "操作",
                dataIndex: 'processInfo',
                width: 90,
                render(text, record) {
                    return (
                        <p>
                            <span onClick={_this.toView2(record)} style={{"cursor": "pointer"}}>编辑</span><br/>
                            {_this.isBtn(record)}
                            <br/><span onClick={_this.toView3(record)} style={{"cursor": "pointer"}}>管理预售商品</span>
                        </p>

                    )

                }
            }
        ];

        return <div className='setForm'>
            <Form>
                <Row>
                    <Col span={24}>
                        <Row className='margin-top'>
                            <Col span={6}>
                                <Row>
                                    <Col {...labelCol}></Col>
                                    <Col {...wrapperCol}>
                                        <FormItem
                                            label='预售名称'
                                            {...formItemLayout}
                                        >
                                            {getFieldDecorator('name', {
                                                rules: [{}]
                                            })(
                                                <Input placeholder="请输入预售名称"/>
                                            )}
                                        </FormItem>
                                    </Col>
                                </Row>
                            </Col>
                            <Col span={6}>
                                <Row>
                                    <Col {...labelCol}></Col>
                                    <Col {...wrapperCol}>
                                        <FormItem
                                            label='预售编号'
                                            {...formItemLayout}
                                        >
                                            {getFieldDecorator('id', {
                                                rules: [{}]
                                            })(
                                                <Input placeholder="请输入预售编号"/>
                                            )}
                                        </FormItem>
                                    </Col>
                                </Row>
                            </Col>
                            <Col span={10}>
                                <Row>
                                    <Col {...labelCol}></Col>
                                    <Col {...wrapperCol}>
                                        <FormItem
                                            label='定金支付方式'
                                            {...formItemLayout}
                                        >
                                            {getFieldDecorator('earnestType', {
                                                rules: [{}]
                                            })(
                                                <Select placeholder="请选择定金支付方式">
                                                    <Option key='1'>按金额支付</Option>
                                                    <Option key='2'>全款支付定金</Option>
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>
                                </Row>
                            </Col>
                        </Row>
                        <Row className='margin-top margin-bottom'>
                            <Col span={24} style={{display: this.state.expand ? 'block' : 'none'}}>
                                <Row>
                                    <Col span={6}>
                                        <Row>
                                            <Col {...labelCol}></Col>
                                            <Col {...wrapperCol}>
                                                <FormItem
                                                    label='预售时间'
                                                    {...formItemLayout}
                                                >
                                                    {getFieldDecorator('beginTime', {})(
                                                        <RangePicker
                                                            showTime={true}
                                                            placeholder={['请选择开始时间', '结束时间']}
                                                            format='YYYY-MM-DD HH:mm:ss'
                                                        ></RangePicker>
                                                    )}
                                                </FormItem>
                                            </Col>
                                        </Row>
                                    </Col>
                                </Row>

                            </Col>
                        </Row>
                    </Col>
                </Row>
                <Row>
                    <Col style={{'height': '84px', 'lineHeight': '84px', 'textAlign': 'right'}} span={22}>
                        <Button style={{'marginRight': '5px', "background": "#108ee9", "color": "#fff"}}
                                onClick={e => this.handleSearch(e)}>搜索</Button>
                        <Button style={{'marginLeft': '5px'}} onClick={this.handleReset}>重置</Button>
                        <a style={{marginLeft: 8, fontSize: 12}} onClick={this.toggle}>
                            {this.state.expand ? '收起' : '展开'} <Icon type={this.state.expand ? 'up' : 'down'}/>
                        </a>
                    </Col>
                </Row>
            </Form>
            <Button onClick={this.toView1}
                    style={{marginLeft: '10px', "background": "#108ee9", "color": "#fff"}}>新增预售</Button>
            <Table
                bordered
                columns={columns}
                dataSource={this.state.datalist}
                style={{margin: 10}}
                pagination={false}
            />
            <div className="table_page">
                <Pagination
                    showTotal={total => `共${total}条`}
                    showQuickJumper
                    showSizeChanger
                    // hideOnSinglePage
                    defaultCurrent={1}
                    defaultPageSize={50}
                    pageSize={this.state.pageSize}
                    current={this.state.pageIndex}
                    pageSizeOptions={["50", "100", "200"]}
                    total={total || 0}
                    onShowSizeChange={this.onPageChange}
                    onChange={this.onPageChange}
                />
            </div>
            <Modal
                title="提示"
                visible={this.state.visible}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
            >
                <p>您确认要更改预热状态</p>
            </Modal>
        </div>
    }
}

export default Form.create()(Index);